from flask import Blueprint, request, jsonify
from ..models import Employee, Department, User
from .. import db
from datetime import datetime

bp = Blueprint('employee', __name__, url_prefix='/api/employees')

@bp.route('/', methods=['GET'])
def get_employees():
    # 获取查询参数
    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 10, type=int)
    search = request.args.get('search', '')
    department_id = request.args.get('department_id', type=int)
    
    # 构建查询
    query = Employee.query
    
    if search:
        query = query.filter(
            (Employee.name.like(f'%{search}%')) |
            (Employee.employee_id.like(f'%{search}%'))
        )
    
    if department_id:
        query = query.filter_by(department_id=department_id)
    
    # 执行分页查询
    pagination = query.order_by(Employee.id.desc()).paginate(
        page=page, per_page=per_page, error_out=False
    )
    
    employees = pagination.items
    
    return jsonify({
        'items': [{
            'id': emp.id,
            'employee_id': emp.employee_id,
            'name': emp.name,
            'gender': emp.gender,
            'birth_date': emp.birth_date.strftime('%Y-%m-%d') if emp.birth_date else None,
            'id_card': emp.id_card,
            'phone': emp.phone,
            'email': emp.email,
            'address': emp.address,
            'department_id': emp.department_id,
            'department_name': emp.department.name if emp.department else None,
            'position': emp.position,
            'hire_date': emp.hire_date.strftime('%Y-%m-%d'),
            'status': emp.status
        } for emp in employees],
        'total': pagination.total,
        'pages': pagination.pages,
        'current_page': page
    })

@bp.route('/<int:id>', methods=['GET'])
def get_employee(id):
    employee = Employee.query.get_or_404(id)
    return jsonify({
        'id': employee.id,
        'employee_id': employee.employee_id,
        'name': employee.name,
        'gender': employee.gender,
        'birth_date': employee.birth_date.strftime('%Y-%m-%d') if employee.birth_date else None,
        'id_card': employee.id_card,
        'phone': employee.phone,
        'email': employee.email,
        'address': employee.address,
        'department_id': employee.department_id,
        'department_name': employee.department.name if employee.department else None,
        'position': employee.position,
        'hire_date': employee.hire_date.strftime('%Y-%m-%d'),
        'status': employee.status
    })

@bp.route('/', methods=['POST'])
def create_employee():
    data = request.get_json()
    
    # 验证必填字段
    required_fields = ['employee_id', 'name', 'gender', 'id_card', 'hire_date']
    for field in required_fields:
        if field not in data:
            return jsonify({'error': f'缺少必填字段: {field}'}), 400
    
    # 检查员工ID是否已存在
    if Employee.query.filter_by(employee_id=data['employee_id']).first():
        return jsonify({'error': '员工ID已存在'}), 400
    
    # 检查身份证号是否已存在
    if Employee.query.filter_by(id_card=data['id_card']).first():
        return jsonify({'error': '身份证号已存在'}), 400
    
    # 创建新员工
    employee = Employee(
        employee_id=data['employee_id'],
        name=data['name'],
        gender=data['gender'],
        birth_date=datetime.strptime(data['birth_date'], '%Y-%m-%d') if data.get('birth_date') else None,
        id_card=data['id_card'],
        phone=data.get('phone'),
        email=data.get('email'),
        address=data.get('address'),
        department_id=data.get('department_id'),
        position=data.get('position'),
        hire_date=datetime.strptime(data['hire_date'], '%Y-%m-%d'),
        status=data.get('status', '在职')
    )
    
    db.session.add(employee)
    db.session.commit()
    
    return jsonify({
        'message': '员工创建成功',
        'id': employee.id
    }), 201

@bp.route('/<int:id>', methods=['PUT'])
def update_employee(id):
    employee = Employee.query.get_or_404(id)
    data = request.get_json()
    
    # 更新员工信息
    if 'name' in data:
        employee.name = data['name']
    if 'gender' in data:
        employee.gender = data['gender']
    if 'birth_date' in data:
        employee.birth_date = datetime.strptime(data['birth_date'], '%Y-%m-%d')
    if 'phone' in data:
        employee.phone = data['phone']
    if 'email' in data:
        employee.email = data['email']
    if 'address' in data:
        employee.address = data['address']
    if 'department_id' in data:
        employee.department_id = data['department_id']
    if 'position' in data:
        employee.position = data['position']
    if 'status' in data:
        employee.status = data['status']
    
    db.session.commit()
    
    return jsonify({
        'message': '员工信息更新成功'
    })

@bp.route('/<int:id>', methods=['DELETE'])
def delete_employee(id):
    employee = Employee.query.get_or_404(id)
    
    # 检查是否有关联的工资记录
    if employee.salaries:
        return jsonify({'error': '该员工存在工资记录，无法删除'}), 400
    
    db.session.delete(employee)
    db.session.commit()
    
    return jsonify({
        'message': '员工删除成功'
    }) 